//
//  OAuthViewController.m
//  weibo
//
//  Created by qiuming on 15/12/23.
//  Copyright © 2015年 qiuming. All rights reserved.
//

#import "OAuthViewController.h"
#import <SVProgressHUD.h>
#import <MJExtension.h>
#import "UserAccountModel.h"

@interface OAuthViewController ()<UIWebViewDelegate>

@property (strong, nonatomic) UIWebView *webView;

@end

@implementation OAuthViewController

- (void)loadView {
    self.view = self.webView;
    self.title = @"登录新浪微博";
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonWithTitle:@"取消" imageName:nil target:self action:@selector(cancleBtnClick)];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonWithTitle:@"自动填充" imageName:nil target:self action:@selector(aotuToFill)];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NetworkTools sharedNetwordTool].oauthUrl]];
    
}
/// 开始加载
- (void)webViewDidStartLoad:(UIWebView *)webView {
    
    [SVProgressHUD show];
}

/// 完成加载
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    
    [SVProgressHUD dismiss];
}

// MARK: - UIWebViewDelegate

/// webView开始加载网络请求
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    // 判断加载的URL是否含有回调地址，不是就加载
    if (![request.URL.absoluteString hasPrefix:REDIRECT_URL]) {
        return YES;
    }
    
    // 从返回的地址中截取某段内容
    NSString *query = request.URL.query;
    if ([query hasPrefix:@"code="]) {
        
        NSString *code = [query substringFromIndex:@"code=".length];
        
        DDLogInfo(@"授权码 = %@", code);
        
        //
        [[UserAccountViewModel sharedUserAccount]accessTokenWithCode:code completed:^(BOOL isSuccessed) {
            
            if (!isSuccessed) {
                [SVProgressHUD showInfoWithStatus:@"网络加载出错"];
                return;
            }
            
            DDLogInfo(@"加载成功");
            
        }];
        
    } else {
        DDLogInfo(@"取消授权");
        [self cancleBtnClick];
    }
    
    return NO;
    
}

/// 自动填充
- (void)aotuToFill {
    NSString *js = @"document.getElementById('userId').value = 'daoge10000@sina.cn';" \
    "document.getElementById('passwd').value = 'qqq123';";
    
    [self.webView stringByEvaluatingJavaScriptFromString:js];

}

/// 取消
- (void)cancleBtnClick {
    [SVProgressHUD dismiss];
    [self.view endEditing:YES];
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

// MARK: - 懒加载
- (UIWebView *)webView {
    if (_webView == nil) {
        _webView = [[UIWebView alloc]init];
        _webView.delegate = self;
    }
    return _webView;
}
@end
